<template>
  <div>
    <vTablePage
      :pageConfig="pageConfig"
      :tableData="tableData"
      :total="total"
      @changeEdit="changeEditType"
      @changePageNo="changePageNo"
      @changeSearch="changeSearch"
      @changeSelect="changeSelect"
    >
      <template #tableHeader>
        <div style="margin-bottom: 5px;">
          <el-button type="primary" size="default" @click="addUser">添加用户</el-button>
          <el-button type="danger" size="default" :disabled="selectIdArr.length ? false : true"
            @click="deleteSelectUser">批量删除
          </el-button>
          <el-button type="primary" size="default" :disabled="selectIdArr.length ? false : true"
            @click="exportExcels" plain>批量导出
          </el-button>
        </div>
      </template>
    </vTablePage>
    <!-- 更新添加账户 -->
    <el-drawer v-model="drawer" :append-to-body="true" @close="closeDrawer">
      <template #header>
        <h4>{{ userParams.id ? '更新用户' : '添加用户' }}</h4>
      </template>
      <template #default>
        <el-form :model="userParams" :rules="rules" ref="formRef">
            <el-form-item label="用户姓名" prop="username">
                <el-input placeholder="请您输入用户姓名" v-model="userParams.username"></el-input>
            </el-form-item>
            <el-form-item label="用户昵称" prop="name">
                <el-input placeholder="请您输入用户昵称" v-model="userParams.name"></el-input>
            </el-form-item>
            <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
                <el-input placeholder="请您输入用户密码" v-model="userParams.password"></el-input>
            </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
            <el-button @click="drawer = false">取消</el-button>
            <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 职位分配 -->
    <el-drawer v-model="assigDrawer">
      <template #header>
          <h4>分配角色(职位)</h4>
      </template>
      <template #default>
          <el-form>
              <el-form-item label="用户姓名">
                  <el-input v-model="userParams.username" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="职位列表">
                  <el-checkbox @change="handleCheckAllChange" v-model="checkAll"
                      :indeterminate="isIndeterminate">全选</el-checkbox>
                  <!-- 显示职位的的复选框 -->
                  <el-checkbox-group v-model="userRole" @change="handleCheckedCitiesChange">
                      <el-checkbox v-for="(role, index) in allRole" :key="index" :label="role">{{ role.roleName
                      }}</el-checkbox>
                  </el-checkbox-group>
              </el-form-item>
          </el-form>
      </template>
      <template #footer>
          <div style="flex: auto">
              <el-button @click="assigDrawer = false">取消</el-button>
              <el-button type="primary" @click="confirmClick">确定</el-button>
          </div>
      </template>
    </el-drawer>
    <!-- 删除 -->
    <el-dialog
      v-model="delDialogVisible"
      title="删除"
      width="500"
    >
      <span>确定删除这条数据吗？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="delDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="closeDelete">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import vTablePage from '../../components/tablePage/index.vue'
import { reqSelectUser, reqRemoveUser, reqUserInfo, reqAddOrUpdateUser, reqAllRole, reqSetUserRole } from '@/api/acl/user'
import type { SetRoleData, UserResponseData, Records, User, AllRoleResponseData, AllRole } from '@/api/acl/user/type';
import { exportExcel } from '@/utils/exporExcel'
// 表格配置
const pageConfig = reactive({
  // 是否展示头部
  showHeader: true,
  // 是否展示索引or多选
  showIndex: true,
  showSelection: true,
  // 列表
  columns:[
    {
      label: '用户名',
      prop: 'username',
      search: true // 搜索
    },
    {
      label: '用户名称',
      prop: 'name'
    },
    {
      label: '用户角色',
      prop: 'roleName'
    },
    {
      label: '创建时间',
      prop: 'createTime'
    },
    {
      label: '更新时间',
      prop: 'updateTime'
    },
    {
      label: '操作',
      prop: 'operation',
      isEdit: true,
      isFixed: true
    }
  ],
  // 操作列
  editBtns:[
    {
      text: '分配角色',
      type: 'assignment',
      icon: 'User'
    },
    {
      text: '编辑',
      type: 'edit',
      icon: 'Edit'
    },
    {
      text: '删除',
      type: 'delete',
      icon: 'Delete'
    }
  ]
})
const tableData = ref([])
const total = ref<number>(0)
const pageNo = ref<number>(1)
let keyword = ref<string>('');
let selectIdArr = ref([]);
let drawer = ref<boolean>(false);
const assigDrawer = ref<boolean>(false);
const delDialogVisible = ref<boolean>(false);
const id = ref<number>(0);
let formRef = ref<any>();
//存储全部职位的数据
let allRole = ref<AllRole>([]);
//当前用户已有的职位
let userRole = ref<AllRole>([]);
//全选
const checkAll = ref<boolean>(false);
//控制顶部全选复选框不确定的样式
const isIndeterminate = ref<boolean>(true);
let userParams = reactive<User>({
  username: '',
  name: '',
  password: ''
});
//校验用户名字回调函数
const validatorUsername = (rule: any, value: any, callBack: any) => {
    //用户名字|昵称,长度至少五位
    if (value.trim().length >= 5) {
        callBack();
    } else {
        callBack(new Error('用户名字至少五位'))
    }
}
//校验用户名字回调函数
const validatorname = (rule: any, value: any, callBack: any) => {
    //用户名字|昵称,长度至少五位
    if (value.trim().length >= 5) {
        callBack();
    } else {
        callBack(new Error('用户昵称至少五位'))
    }
}
const validatorPassword = (rule: any, value: any, callBack: any) => {
    //用户名字|昵称,长度至少五位
    if (value.trim().length >= 6) {
        callBack();
    } else {
        callBack(new Error('用户密码至少六位'))
    }
}
//表单校验的规则对象
const rules = {
    //用户名字
    username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
    //用户昵称
    name: [{ required: true, trigger: 'blur', validator: validatorname }],
    //用户的密码
    password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
}

// 编辑类型
const changeEditType = (val: any) => {
  const { item, row } = val
  if (item.type === 'assignment') {
    changeRole(row)
  } else if (item.type === 'edit') {
    changeEdit(row)
  } else if (item.type === 'delete') {
    id.value = row.id
    delDialogVisible.value = true
  }
}
// 分配角色
const changeRole = async(row: any) => {
  //存储已有的用户信息
  Object.assign(userParams, row);
  //获取全部的职位的数据与当前用户已有的职位的数据
  let result: AllRoleResponseData = await reqAllRole((userParams.id as number));
  if (result.code == 200) {
      //存储全部的职位
      allRole.value = result.data.allRolesList;
      //存储当前用户已有的职位
      userRole.value = result.data.assignRoles;
      //抽屉显示出来
      assigDrawer.value = true;
  }
}
//全部复选框的change事件
const handleCheckAllChange = (val: boolean) => {
    //val:true(全选)|false(没有全选)
    userRole.value = val ? allRole.value : [];
    //不确定的样式(确定样式)
    isIndeterminate.value = false
}
//复选框的change事件
const handleCheckedCitiesChange = (value: string[]) => {
    //代表:勾选上的项目个数与全部的职位个数相等，顶部的复选框勾选上
    checkAll.value = value.length === allRole.value.length;
    //不确定的样式
    isIndeterminate.value = value.length !== allRole.value.length
}
//确定按钮的回调(分配职位)
const confirmClick = async () => {
  //收集参数
  let data: SetRoleData = {
      userId: (userParams.id as number),
      roleIdList: userRole.value.map(item => {
          return (item.id as number)
      })
  }
  //分配用户的职位
  let result: any = await reqSetUserRole(data);
  if (result.code == 200) {
      ElMessage({ type: 'success', message: '分配职务成功' });
      assigDrawer.value = false;
      getList();
  }
}

// 分页
const changePageNo = (row: any) => {
  pageNo.value = row
  getList()
}
// 搜索
const changeSearch = (row: any) => {
  keyword.value = row.username ? row.username : ''
  getList()
}
// 获取选中数据
const changeSelect = (row: any) => {  
  selectIdArr.value = row
}
// 添加用户
const addUser = () => {
  drawer.value = true
  Object.assign(userParams, {
    id: 0,
    username: '',
    name: '',
    password: ''
  })
}
// 编辑用户
const changeEdit = (row: any) => {
  Object.assign(userParams, row)
  drawer.value = true
}
// 保存添加
const save = async() => {
  await formRef.value.validate()
  let result: any = await reqAddOrUpdateUser(userParams);
  //添加或者更新成功
  if (result.code == 200) {
      //关闭抽屉
      drawer.value = false;
      //提示消息
      ElMessage({ type: 'success', message: userParams.id ? '更新成功' : '添加成功' });
      //浏览器自动刷新一次
      // window.location.reload();
      getList()
  } else {
      //关闭抽屉
      drawer.value = false;
      //提示消息
      ElMessage({ type: 'error', message: userParams.id ? '更新失败' : '添加失败' });
  }
}
// 关闭抽屉
const closeDrawer = () => {  
  //清空表单
  formRef.value.resetFields();
  //清空userParams
  Object.assign(userParams, {
      username: '',
      name: '',
      password: ''
  });
}
// 删除
const closeDelete = async () => {
  let result: any = await reqRemoveUser(id.value);
  if (result.code == 200) {
    ElMessage({ type: 'success', message: '删除成功' });
    delDialogVisible.value = false;
    getList()
  }
}
// 批量删除
const deleteSelectUser = async() => {
  let idsList: any = selectIdArr.value.map(item => {
      return item.id;
  });
  //批量删除的请求
  let result: any = await reqSelectUser(idsList);
  if (result.code == 200) {
    pageNo.value = 1
    ElMessage({ type: 'success', message: '删除成功' });
    getList()
  }
}
// 导出
const exportExcels = () => {
  exportExcel(pageConfig.columns, selectIdArr.value, '用户列表')
  
}
// 获取列表
const getList = async() => {
  let result: UserResponseData = await reqUserInfo(pageNo.value, keyword.value);
  if (result.code == 200) {
      total.value = result.data.total;
      tableData.value = result.data.records;
  }
}
onMounted(() => {  
  getList()  
})

</script>

<style scoped lang="scss">

</style>